import React, { Component } from 'react'
import 'antd/dist/antd.css'; 
import store from './store/index.js'
import { changeValue, addList, deleteItem} from './store/action'
import TodoListUI from './TodoListUI'
import axios from 'axios'


class TodoList extends Component{

  constructor(props){
    super(props);
    this.state=store.getState();
    this.handleChange = this.handleChange.bind(this);
    this.additem = this.additem.bind(this);
    this.handleState = this.handleState.bind(this);
    this.deleteitem = this.deleteitem.bind(this)
    store.subscribe(() =>
      this.handleState()
    )
  }

  componentDidMount() {
    //ajax请求获取数据
    axios.get('https://www.easy-mock.com/mock/5bc0699fa6a4301649d22e4f/react.mock')
      .then((response) => {
        console.log(response)
      })
      .catch((error) => {
        console.log(error);
      });
  }

  render(){
    return (
      <TodoListUI 
        inputValue={this.state.inputValue}
        handleChange={this.handleChange}
        additem={this.additem}
        list={this.state.list}
        deleteitem={this.deleteitem}
      />
    )
  }
  //方法
  //改变input的值
  handleChange(e){
    store.dispatch(changeValue(e.target.value))
  }
  //增加列表
  additem(){
    let list=[this.state.inputValue, ...this.state.list]
    store.dispatch(addList(list))
  }
  //监听store后更新state方法
  handleState(){
    this.setState(store.getState())
  }
  //删除列表
  deleteitem(index){
    store.dispatch(deleteItem(index))
  }
}


export default TodoList
